<script setup>
import { ref, onMounted, watch } from 'vue'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import request from '../../utils/sj-request'

const props = defineProps({
  subjectId: {
    type: Number,
    required: true
  },
  refresh: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  // 新增参数，用于级联选择
  bigQuestionId: {
    type: Number,
    default: null
  },
  questionTypeId: {
    type: Number,
    default: null
  },
  hardLevel: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['select', 'refresh'])

// 知识点树数据
const knowledgePoints = ref([])
// 加载状态
const loading = ref(false)
// 搜索关键词
const searchKeyword = ref('')
// 当前选中的节点
const currentNode = ref(null)
// 默认展开的节点
const defaultExpandedKeys = ref([])
// 过滤后的知识点树数据
const filteredKnowledgePoints = ref([])

// 获取知识点树
const fetchKnowledgePointTree = async () => {
  loading.value = true
  try {
    // 检查是否有额外的查询参数（用于组卷方案）
    const bigQuestionId = props.bigQuestionId
    const questionTypeId = props.questionTypeId
    const hardLevel = props.hardLevel
    
    // 根据是否有额外参数决定调用哪个API
    const apiUrl = (bigQuestionId && questionTypeId && hardLevel) 
      ? 'knowledge-point/tree/question-count' 
      : 'knowledge-point/tree'
    
    const params = {
      subjectId: props.subjectId
    }
    
    // 如果有额外参数，添加到请求中
    if (bigQuestionId) params.bigQuestionId = bigQuestionId
    if (questionTypeId) params.questionTypeId = questionTypeId
    if (hardLevel) params.hardLevel = hardLevel
    
    const res = await request({
      url: apiUrl,
      method: 'get',
      params
    })
    
    if (res.code === 200) {
      knowledgePoints.value = res.data || []
      // 应用搜索过滤
      applySearchFilter()
      // 设置默认展开的节点（一级节点）
      defaultExpandedKeys.value = knowledgePoints.value.map(item => item.id)
    } else {
      // 处理详细错误信息，优先显示data中的错误详情
      if (res.data && typeof res.data === 'object') {
        // 如果data是对象，提取所有错误信息并显示
        const errorDetails = Object.values(res.data).filter(v => v).join('，');
        if (errorDetails) {
          ElMessage.warning(errorDetails);
          return;
        }
      }
      ElMessage.warning(res.message || '获取知识点树失败')
    }
  } catch (error) {
    console.error('获取知识点树失败:', error)
    ElMessage.error('获取知识点树失败')
  } finally {
    loading.value = false
  }
}

// 过滤知识点树
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.toLowerCase().includes(value.toLowerCase())
}

// 深度搜索知识点树
const searchTree = (nodes, keyword) => {
  if (!nodes || nodes.length === 0) return []
  
  return nodes.filter(node => {
    // 检查当前节点是否匹配
    const isMatch = node.name.toLowerCase().includes(keyword.toLowerCase())
    
    // 递归搜索子节点
    const matchingChildren = searchTree(node.children, keyword)
    
    // 如果有匹配的子节点，保留这些子节点
    if (matchingChildren.length > 0) {
      node.children = matchingChildren
      return true
    }
    
    // 如果当前节点匹配，则保留
    return isMatch
  })
}

// 应用搜索过滤
const applySearchFilter = () => {
  if (!searchKeyword.value) {
    // 如果没有搜索关键词，显示完整树
    filteredKnowledgePoints.value = [...knowledgePoints.value]
  } else {
    // 深拷贝知识点树，避免修改原始数据
    const treeCopy = JSON.parse(JSON.stringify(knowledgePoints.value))
    // 应用搜索过滤
    filteredKnowledgePoints.value = searchTree(treeCopy, searchKeyword.value)
  }
}

// 处理搜索输入
const handleSearchInput = (val) => {
  // 如果清空了搜索关键词，重置过滤
  if (!val) {
    handleClearSearch()
  }
}

// 处理搜索按钮点击
const handleSearch = () => {
  applySearchFilter()
}

// 处理清空搜索
const handleClearSearch = () => {
  searchKeyword.value = ''
  applySearchFilter()
}

// 处理节点点击
const handleNodeClick = (data) => {
  // 如果是组卷方案模式且试题数量为0，则不允许选择
  if (props.bigQuestionId && props.questionTypeId && props.hardLevel && data.questionCount === 0) {
    ElMessage.warning('该知识点下没有符合条件的试题，请选择其他知识点')
    return
  }
  
  currentNode.value = data
  emit('select', data)
}

// 添加知识点
const handleAddNode = (parentNode) => {
  emit('select', {
    id: null,
    parentId: parentNode ? parentNode.id : 0,
    subjectId: props.subjectId,
    name: '',
    sortOrder: 0,
    isNew: true
  })
}

// 编辑知识点
const handleEditNode = (node) => {
  emit('select', { ...node, isEdit: true })
}

// 删除知识点
const handleDeleteNode = (node) => {
  ElMessageBox.confirm(`确定要删除知识点「${node.name}」吗？删除后不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await request({
        url: `/knowledge-point/${node.id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除知识点成功')
        // 重新加载知识点树
        fetchKnowledgePointTree()
        emit('refresh')
      } else {
        // 处理详细错误信息，优先显示data中的错误详情
        if (res.data && typeof res.data === 'object') {
          // 如果data是对象，提取所有错误信息并显示
          const errorDetails = Object.values(res.data).filter(v => v).join('，');
          if (errorDetails) {
            ElMessage.error(errorDetails);
            return;
          }
        }
        // 如果没有详细错误信息，则显示message
        ElMessage.error(res.message || '删除知识点失败')
      }
    } catch (error) {
      console.error('删除知识点失败:', error)
      ElMessage.error('删除知识点失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 监听刷新属性变化
watch(() => props.refresh, (newVal) => {
  if (newVal) {
    fetchKnowledgePointTree()
  }
})

// 监听学科ID变化
watch(() => props.subjectId, (newVal) => {
  if (newVal) {
    fetchKnowledgePointTree()
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchKnowledgePointTree()
})

// 监听搜索关键词变化
watch(() => searchKeyword.value, (newVal) => {
  // 当用户输入搜索关键词时，自动应用过滤
  applySearchFilter()
})
</script>

<template>
  <div class="knowledge-point-tree-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索知识点"
        clearable
        prefix-icon="el-icon-search"
        @input="handleSearchInput"
        @clear="handleClearSearch"
      >
        <template #prefix>
          <el-icon><search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch" class="search-button">
        <el-icon><search /></el-icon> 搜索
      </el-button>
      <el-button type="primary" @click="handleAddNode(null)" class="add-button" :disabled="props.readonly">
        <el-icon><plus /></el-icon> 添加顶级知识点
      </el-button>
    </div>
    
    <!-- 知识点树 -->
    <div class="tree-container" v-loading="loading">
      <el-tree
        v-if="filteredKnowledgePoints.length > 0"
        :data="filteredKnowledgePoints"
        :props="{
          label: 'name',
          children: 'children'
        }"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        highlight-current
        @node-click="handleNodeClick"
      >
        <template #default="{data }">
          <div class="custom-tree-node" :class="{ 'disabled-node': data.questionCount === 0 && (props.bigQuestionId && props.questionTypeId && props.hardLevel) }">
            <span class="node-label">
              {{ data.name }}
              <!-- 如果有试题数量信息，显示数量标签 -->
              <el-tag 
                v-if="data.questionCount !== undefined" 
                size="small" 
                :type="data.questionCount > 0 ? 'success' : 'info'"
                class="count-tag"
              >
                {{ data.questionCount }}
              </el-tag>
            </span>
            <span class="node-actions">
              <el-button link type="primary" size="small" @click.stop="handleAddNode(data)" :disabled="props.readonly">
                <el-icon><plus /></el-icon>
              </el-button>
              <el-button link type="primary" size="small" @click.stop="handleEditNode(data)" :disabled="props.readonly">
                <el-icon><edit /></el-icon>
              </el-button>
              <el-button link type="danger" size="small" @click.stop="handleDeleteNode(data)" :disabled="props.readonly">
                <el-icon><delete /></el-icon>
              </el-button>
            </span>
          </div>
        </template>
      </el-tree>
      <el-empty v-else description="暂无知识点数据" />
    </div>
  </div>
</template>

<style scoped>
.knowledge-point-tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-container {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.tree-container {
  flex: 1;
  overflow: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  font-size: 14px;
}

.node-actions {
  display: none;
}

.custom-tree-node:hover .node-actions {
  display: inline-block;
}

.add-button, .search-button {
  white-space: nowrap;
}

.search-button {
  margin-right: 5px;
}
</style>